package org.example.pinda.auth.util;

import org.springframework.util.Assert;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * Rsa Key工具类
 */
public class RsaKeyHelper {

    /**
     * 获取公钥,用于解析token
     */
    public PublicKey getPublicKey(String filename)
            throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
        InputStream resourceAsStream =
                this.getClass().getClassLoader().getResourceAsStream(filename);
        Assert.notNull(resourceAsStream, "file cannot be null");
        try (DataInputStream dis = new DataInputStream(resourceAsStream)) {
            byte[] bytes = new byte[resourceAsStream.available()];
            dis.readFully(bytes);
            X509EncodedKeySpec spec = new X509EncodedKeySpec(bytes);
            KeyFactory kf = KeyFactory.getInstance("RSA");
            return kf.generatePublic(spec);
        }
    }

    /**
     * 获取公钥,用于生成token
     */
    public PrivateKey getPrivateKey(String filename)
            throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(filename);
        Assert.notNull(resourceAsStream, "file cannot be null");
        try (DataInputStream dis = new DataInputStream(resourceAsStream)) {
            byte[] keyBytes = new byte[resourceAsStream.available()];
            dis.readFully(keyBytes);
            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory kf = KeyFactory.getInstance("RSA");
            return kf.generatePrivate(spec);
        }
    }

}
